﻿using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Rigidbody))]
public class EnemyAI : MonoBehaviour 
{

	public float movementSpeed;
	public float distanceToPlayer;
	public GameObject explosion;
	public float damageRange;
	public float damageOnExplosion;
	public EnemyRoomController enemyController;
	
	private Transform myTransform;
	private Rigidbody myRigidbody;
	private GameObject myTarget;
	
	void Start ()
	{
		myTransform = transform;
		myRigidbody = rigidbody;
		myTarget = null;
		enemyController = GameObject.Find("_EnemyRoomHandler").GetComponent<EnemyRoomController>();
	}
	
	void Update()
	{
		if (myTarget != null)
		{
			Vector3 posToTarget = myTarget.transform.position - myTransform.position;
			Vector3 desiredVelocity = Vector3.Normalize(posToTarget) * movementSpeed;
			Vector3 currentVelocity = myRigidbody.velocity;
			Vector3 steeringForce = desiredVelocity - currentVelocity;
			myRigidbody.velocity += steeringForce * Time.deltaTime;

			if(posToTarget.sqrMagnitude <= distanceToPlayer)
			{
				Explodes (distanceToPlayer);
			}
		}
	}

	void OnTriggerStay(Collider other)
	{
		if(other.gameObject.CompareTag("Player"))
		{
			myTarget = other.gameObject;
		}
	}

	void OnTriggerExit(Collider other)
	{
		myRigidbody.velocity = Vector3.zero;
		myTarget = null;
	}

	public void Explodes(float distance)
	{
		if(distance <= damageRange)
		{
			HealthPickup health = GameObject.FindGameObjectWithTag("Player").GetComponent<HealthPickup>();
			if(health != null)
			{
				float damageDealt = 0.0f;
				if(damageRange != 0.0f)
				{
					damageDealt = Mathf.Round(((damageRange - distance) / damageRange) * damageOnExplosion); //Damage multiplier depending on the distance
				}
				if(damageDealt > 0)
				{
					health.TakeDamage(damageDealt);
				}
			}
		}
		enemyController.DecreaseEnemyCount();
		Instantiate (explosion, myTransform.position, Quaternion.identity);
		Destroy(gameObject);
	}
}
